var http = require("http");

/*
callback(is_success, data/erro)
*/
// get请求的参数，是带在URL的地址上面的
function http_get(ip, port, url, params, callback) {
	// step1,创建一个 http.ClientRequest
	var options = {
		host: "127.0.0.1",
		port: port,
		path: url + "?" + params,
		method: "GET"
	};

	// 当有请求返回的时候，参数就会被传递为http.IncomingMessage
	var req = http.request(options, function(incoming_msg) {
		console.log("respones status " + incoming_msg.statusCode);

		// 监听IncomingMessage的data事件，当收到服务器发过来的数据的时候，触发这个事件
		incoming_msg.on("data", function(data) {
			if (incoming_msg.statusCode === 200) {
				callback(true, data);
			}
		});
		 
	});

	// 把这个请求发送出去
	req.end();
}


//访问 get login
// http_get("127.0.0.1", 6080, "/login", "uname=xiaoming&upwd=123456", function(is_ok, data) {
// 	if (is_ok) {
// 		console.log(data.toString());
// 	}
// });


// post可以带body数据传到服务器
function http_post(ip, port, url, params, body, callback) {
	// step1,创建一个 http.ClientRequest
	var options = {
		host: "127.0.0.1",
		port: port,
		path: url + "?" + params,
		method: "POST",

		headers: {
			"Content-Type": "application/x-www-form-urlencoded",
			"Content-Length": body.length
		}
	};

	var req = http.request(options, function(incoming_msg) {
		console.log("respones status " + incoming_msg.statusCode);

		// 监听IncomingMessage的data事件，当收到服务器发过来的数据的时候，触发这个事件
		incoming_msg.on("data", function(data) {
			if (incoming_msg.statusCode === 200) {
				callback(true, data);
			}
		});
		 
	});

	// step2 写入body数据
	req.write(body);

	// 发送请求
	req.end();
}


//访问post  uploads上传文件
http_post("127.0.0.1", 6080, "/upload", "filename=my_file.txt", "Hello Htpp Post", function(is_ok, data) {
	if (is_ok) {
		console.log("upload_success", data.toString());	
	}
});